package com.example.crmweb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.crmweb.entity.Role;
import com.example.crmweb.entity.RoleAuth;
import com.example.crmweb.mapper.RoleMapper;
import com.example.crmweb.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.crmweb.lang.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import javax.annotation.Resource;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author -CRM-
 * @since 2022-03-18
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private RoleMapper roleMapper;
    QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
    /**
     * 插入角色
     *
     * @return
     */
    @Override
    public Result create(Role role) {
//        判断角色名是否重复
        Role name = roleMapper.selectOne(roleQueryWrapper.eq("name", role.getName()));
        if (name != null) {
            return Result.fail("该角色已经存在，请查证后再添加！");
        }
        int insert = roleMapper.insert(role);
        return Result.success(200,"添加成功",insert);

    }

    /**
     * 修改角色
     * @param role
     * @return
     */
    @Override
    public Result modify(Role role) {
//        先判断是否传入role的id
        if (role.getId() == null) {
            return Result.fail("修改失败");
        }
//        根据角色id修改角色
        int update = roleMapper.updateById(role);
        if (update==1){
            return Result.success(200,"修改成功",update);
        }else {
            return Result.fail("修改失败");
        }

    }

    /**
     * 删除角色
     * @param id
     * @return
     */
    @Override
    public Result delete(Integer id) {
//        根据id查找角色
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        Role role = roleMapper.selectOne(roleQueryWrapper.eq("id", id));
        if (role!=null){
//            如果角色不为空，删除
            int delete = roleMapper.deleteById(id);
            return Result.success(200,"删除成功",delete);
        }else {
            return Result.fail("删除失败，没有这个角色");
        }

    }
}
